package vip.lsjscl.flowboot.workflow.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import vip.lsjscl.flowboot.util.constants.TaskStatus;
import vip.lsjscl.flowboot.workflow.entity.DKRuntimeTask;

import java.util.Date;
import java.util.List;

/**
 * 运行时任务存储库
 *
 * @author zhangxingju
 * @date 2025/02/14
 */
@Repository
public interface DKRuntimeTaskRepository extends JpaRepository<DKRuntimeTask, String> {

    // 根据业务ID和任务状态查找唯一待办理任务记录（假设每个业务只有一条待办理任务）
    DKRuntimeTask findByIdAndStatus(String id, TaskStatus status);


    // 查询所有不同的业务ID
    @Query("SELECT DISTINCT r.businessId FROM DKRuntimeTask r WHERE r.createTime >= :twoDaysAgo")
    List<String> findDistinctBusinessIds(@Param("twoDaysAgo") Date twoDaysAgo);


    // 根据业务ID查询所有任务
    List<DKRuntimeTask> findByBusinessId(String businessId);

    // 根据人员ID和任务状态查询任务
    @Query(value = """
             SELECT ht.* FROM dk_runtime_task ht inner join dk_activity ac 
             on ht.activity_id = ac.id WHERE ac.approvers like concat('%',:userId,'%') AND ht.status = :status
            """, nativeQuery = true)
    List<DKRuntimeTask> findByUserIdAndStatus(@Param("userId") String userId, @Param("status") int status);

    // 根据部门ID和任务状态查询任务
    @Query(value = """
             SELECT ht.* FROM dk_runtime_task ht inner join dk_activity ac 
             on ht.activity_id = ac.id WHERE ac.departments like concat('%',:deptId,'%') AND ht.status = :status
            """, nativeQuery = true)
    List<DKRuntimeTask> findByDeptIdAndStatus(@Param("deptId") String deptId, int status);

    // 根据人员ID或部门ID查询待办任务
    @Query(value = """
             SELECT ht.* FROM dk_runtime_task ht inner join dk_activity ac on ht.activity_id = ac.id 
             WHERE (ac.departments like concat('%',:deptId,'%') or ac.approvers like concat('%',:userId,'%')) AND ht.status = :status
            """, nativeQuery = true)
    List<DKRuntimeTask> findByUserIdOrDeptIdAndStatus(@Param("userId") String userId, @Param("deptId") String deptId, int status);


    Long countByBusinessId(String businessId);

    // 根据人员ID和任务状态查询任务
    @Query(value = "SELECT ht.* FROM dk_runtime_task ht inner join dk_activity ac on ht.activity_id = ac.id " +
            "WHERE ac.approvers like concat('%',:userId,'%') " +
            "AND ac.code =:code " +
            "AND ht.status = :status", nativeQuery = true)
    List<DKRuntimeTask> findByUserIdAndStatusAndActivityCode(@Param("userId") String userId, @Param("code") String code, @Param("status") int status);

}